package edu.harvard.s3xyback;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: Ryan
 * Date: 11/27/12
 * Time: 3:43 PM
 * Helps provide a GUI interface for the S3xyBack Class
 *
 * A class that extends JFrame in order to create the main window
 * for the S3xyBack configuration
 */

public class S3xyWindow extends JFrame
    implements ActionListener
{
    // declares components of window that are not a JTextField or JPasswordField
    private JButton fileButton;
    private JButton saveButton;
    private JComboBox reportSched;
    private JCheckBox autoRestoreBox;
    private JFileChooser fileSelector = new JFileChooser();
    private JTextArea textArea;
    private JScrollPane scrollPane;

    // declares panels inserted in main window
    private JPanel configPane;
    private JPanel filePane;
    private JPanel inputPane;
    private JPanel savePane;
    private JPanel selectionPane;
    private JPanel titlePane;

    // declares Fields for main window
    private JPasswordField awsField;
    private JPasswordField passphraseField;
    private JPasswordField secretField;
    private JTextField configPathField;
    private JTextField checkDays;

    // declares array to store directories
    String directories[];

    /**
     * A constructor for S3xyWindow which takes no parameters.
     */
    public S3xyWindow()
    {
        // sets up basic features of S3xyWindow
        this.setTitle("S3xy Back");
        this.setSize(775,650);
        this.setLocation(300,50);

        // Adds all JComponents to S3xyWindow.
        addComponents();

        // sets default close operation to exit upon closing
        // done so that program terminates if user clicks x in top-right corner
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // allows S3xyWindow to be visible
        this.setVisible(true);
    }

    /**
     * Declares (as needed) and initializes the JComponents needed
     * for the window.  Then, one by one, adds each component to S3xyWindow.
     */
    public void addComponents()
    {
        // sets layout managaer for S3xyWindow as BoxLayout
        Container content = this.getContentPane();
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

        // declares variable to store logo image
        ImageIcon testImage = new ImageIcon("C:\\Users\\Ryan\\Documents\\codingProjects\\s3xyback\\java\\src\\edu\\harvard\\s3xyback\\S3xyBack2.png");

        // declares a new label and sets properties
        // title to be placed at top of window
        JLabel title = new JLabel(testImage);
        title.setFont(new Font("Times New Roman", Font.PLAIN, 40));

        // declares new JPanel to store title
        titlePane = new JPanel(new GridLayout(0,3));

        // padding for titlePane
        JLabel padding = new JLabel("");
        JLabel padding2 = new JLabel("");

        // adds components to titlePane
        titlePane.add(padding);
        titlePane.add(title);
        titlePane.add(padding2);

        // creates a panel for aws and password fields
        createInputPane();

        // creates a panel to select directories to be stored
        createFilePane();

        // creates panel to ask user for the desired path of the configuration file
        createConfigPane();

        // creates drop-down box to select frequency of reports
        String sched[] = {"","DAILY", "WEEKLY", "MONTHLY"};
        reportSched = new JComboBox(sched);
        reportSched.setSelectedIndex(0);

        // creates corresponding label for reportSched
        JLabel reportLabel = new JLabel("Report Frequency");
        reportLabel.setLabelFor(reportSched);

        // creates checkbox to indicate whether or not auto-restore would be constantly active
        autoRestoreBox = new JCheckBox("Auto-Restore?");
        autoRestoreBox.setMnemonic(KeyEvent.VK_C);
        autoRestoreBox.setSelected(false);

        // creates field to take in checkDays, frequency of checking file integrity
        checkDays = new JTextField(2);
        JLabel checkLabel = new JLabel("Check days: ");
        checkLabel.setLabelFor(checkDays);

        // adds drop down box and check box to selectionPane
        selectionPane = new JPanel(new FlowLayout(FlowLayout.LEADING));
        selectionPane.add(checkLabel);
        selectionPane.add(checkDays);
        selectionPane.add(Box.createHorizontalStrut(166));
        selectionPane.add(reportLabel);
        selectionPane.add(reportSched);
        selectionPane.add(Box.createHorizontalStrut(166));
        selectionPane.add(autoRestoreBox);

        // creates a "save" button
        // user clicks it to have info stored
        saveButton = new JButton("Save");
        rootPane.setDefaultButton(saveButton);

        // adds action listeners to save button
        saveButton.addActionListener(this);

        // creates a new JPanel with FlowLayout to be placed within main JFrame
        // adds button at bottom-right of window
        savePane = new JPanel(new FlowLayout(FlowLayout.TRAILING));

        // adds save button to savePane
        savePane.add(saveButton);

        // adds components, in order they appear, to S3xyWindow
        add(titlePane);
        add(inputPane);

        add(Box.createVerticalStrut(10));

        add(configPane);
        add(filePane);

        add(Box.createVerticalStrut(25));

        add(selectionPane);
        add(savePane);
    }

    /**
     * Listens for an ActionEvent (a button click) from S3xyWindow, determines
     * which button has been clicked and then takes the appropriate actions.
     * @param e ActionEvent that is a button click from S3xyWindow
     */
    public void actionPerformed(ActionEvent e)
    {
        // checks if "Select Directories" button has been clicked
        if (e.getSource() == fileButton)
        {
            // allows user to select both files and directories
            fileSelector.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            // opens dialog window for user to select files/directories
            fileSelector.setDialogTitle("Directory Selector");
            int result = fileSelector.showOpenDialog(this);

            // Accounts for scenario where user clicks open in file chooser dialog window
            if (result == JFileChooser.APPROVE_OPTION)
            {
                // gets file that user selected
                File file = fileSelector.getSelectedFile();

                // appends file path to textArea
                textArea.append(file.getPath() + "\n");
            }
        }

        // checks if "Save" button has been clicked
        else if (e.getSource() == saveButton)
        {
            // loads all user input from fields into local variables
            String awsKey = awsField.getText();
            String configPath = configPathField.getText();
            String passphrase = passphraseField.getText();
            String secretKey = secretField.getText();
            String schedule = reportSched.getSelectedItem().toString();
            String checkindays = checkDays.getText();

            // stores String in restore variable based on boolean
            String restore;
            boolean r = autoRestoreBox.isSelected();
            if (r == true)
                restore = "true";
            else
                restore = "false";

            // loads selected directories and files into string array
            directories = (textArea.getText()).split("\n");

            // creates new instance of ConfigClient with indicated configuration file path
            ConfigClient setUp = new ConfigClient(configPath + "\\my_properties.properties");

            // closes current instance of S3xyWindow
            this.dispose();

            // creates configuration file with indicated values
            setUp.createConfigFile(awsKey, secretKey, directories, checkindays,schedule, restore);
        }
    }

    /**
     * Creates a new JPanel with FlowLayout layout manager which has
     * the "Select Directories" button as well as a JText Area to display
     * each currently selected directory or file path.
     */
    public void createFilePane()
    {
        filePane = new JPanel(new FlowLayout(FlowLayout.LEADING));

        // creates button for selecting directories
        // links to JDialog window with a file chooser
        fileButton = new JButton("Select Directories");
        fileButton.setAlignmentX(1f);
        filePane.add(fileButton);

        // adds action listener to fileButton
        fileButton.addActionListener(this);

        // creates new JTextArea and sets properties
        // used to display which directories have been selected
        textArea = new JTextArea(5, 51);
        textArea.setEditable(true);
        scrollPane = new JScrollPane(textArea);
        filePane.add(scrollPane);

    }

    /**
     * Creates a JPanel with FlowLayout manager that has the JLabel
     * for config file path added in first, then the corresponding JTextArea
     * for config file path name.
     */
    public void createConfigPane()
    {
        // creates a new JPanel with FlowLayout to be placed within main JFrame
        configPane = new JPanel(new FlowLayout(FlowLayout.LEADING));

        // creates a JTextField for user to indicate desired file path
        configPathField = new JTextField(51);

        // creates corresponding label for filePathField
        JLabel pathLabel = new JLabel("Enter Config Path: ");
        pathLabel.setLabelFor(configPathField);

        // adds file path and label
        // adds padding at beginning
        configPane.add(Box.createHorizontalStrut(25));
        configPane.add(pathLabel);
        configPane.add(configPathField);
    }

    /**
     * Creates a JPanel with the GridLayout layout manager which
     * contains the JTextArea's for passphrase, AWS access key,
     * and secret as well as their corresponding JLabels.
     */
    public void createInputPane()
    {
        // declares a JPasswordField for passphrase input
        passphraseField = new JPasswordField(15);

        // creates corresponding label for passphrase field
        JLabel passphraseLabel = new JLabel("Enter passphrase: ");
        passphraseLabel.setLabelFor(passphraseField);

        // declares a JPasswordField for aws key input
        awsField = new JPasswordField(25);

        // creates corresponding label for aws key field
        JLabel awsLabel = new JLabel("Enter AWS Access Key: ");
        awsLabel.setLabelFor(passphraseField);
        awsField.setAlignmentX(Component.RIGHT_ALIGNMENT);

        // declares a JPasswordField for secret key input
        secretField = new JPasswordField(25);

        // creates corresponding lable for secret key field
        JLabel secretLabel = new JLabel("Enter AWS Secret Key: ");
        secretLabel.setLabelFor(secretField);

        // creates a new JPanel with GridLayout to be placed within main JFrame
        inputPane = new JPanel(new GridLayout(0,4));

        // empty labels for padding
        JLabel padding1 = new JLabel("");
        JLabel padding2 = new JLabel("");
        JLabel padding3 = new JLabel("");
        JLabel padding4 = new JLabel("");
        JLabel padding5 = new JLabel("");
        JLabel padding6 = new JLabel("");

        // adds passphrase field with padding on margins
        inputPane.add(padding1);
        inputPane.add(passphraseLabel);
        inputPane.add(passphraseField);
        inputPane.add(padding2);

        // adds aws key field with padding on margins
        inputPane.add(padding3);
        inputPane.add(awsLabel);
        inputPane.add(awsField);
        inputPane.add(padding4);

        // adds secret key with padding on margins
        inputPane.add(padding5);
        inputPane.add(secretLabel);
        inputPane.add(secretField);
        inputPane.add(padding6);
    }
}
